package com.xxx.seckill.rabbitmq;

import com.xxx.seckill.pojo.TSeckillOrder;
import com.xxx.seckill.pojo.TUser;
import com.xxx.seckill.service.TGoodsService;
import com.xxx.seckill.service.TOrderService;
import com.xxx.seckill.utils.JsonUtil;
import com.xxx.seckill.vo.GoodsVo;
import com.xxx.seckill.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: xxx
 * @Date: 2023/1/10 21:17
 * @Description: 接收秒杀信息
 */
@Service
@Slf4j
public class MQReceiverFromSeckill {
    
    @Autowired
    private TGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TOrderService orderService;
    
    /**
     * 下订单操作
     * @param message
     */
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message){
        log.info("接收的消息 ： " + message);
        //转成对象
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message,SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        TUser user = seckillMessage.getUser();
        
        //判断库存
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if(goodsVo.getStockCount() < 1){
            return;
        }
        
        // 判断是否重复抢购
        TSeckillOrder seckillOrder =
                (TSeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if(seckillOrder != null){   
            // 秒杀预定不为空，意思就是已经有了秒杀记录，因为只能秒杀一件，所以返回到秒杀错误界面
            return;
        }
        // 下单操作
        orderService.seckill(user,goodsVo);
    }
    
}
